package com.sk.util.model;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.sk.util.SpringUtil;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

/**
 * @author smy
 * {@code @date} 2022/10/26
 */
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "标准返回模型")
public class Result<T> {
    @Schema(description = "结果编号,0=成功")
    private int code;
    @Schema(description = "结果描述")
    private String message;
    @Schema(description = "应用名称")
    private String application ;
    @Schema(description = "结果数据")
    private T data;

    public Result(int code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
        this.application = SpringUtil.getApplication();
    }

    public static Result<?> success() {
        return new Result<>(0, null, null);
    }

    public static <T> Result<T> success(T data) {
        return new Result<>(0, null, data);
    }

    public static Result<?> fail(int code, String message) {
        return new Result<>(code, message, null);
    }

    public static <T> Result<T> fail(int code, String message, T data) {
        return new Result<>(code, message, data);
    }

    public static <D> Result<D> parseJSON(Class<D> dataClass, String content) {
        return JSONObject.parseObject(content, new TypeReference<Result<D>>(dataClass) {
        });
    }

}
